package com.lancoo.znbkxx.teacher.diagnosis

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.view.animation.DecelerateInterpolator
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.studyAnalysis.StuStudyAnalysisActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.studyAnalysis.StudyAnalysisActivity
import com.lancoo.znbkxx.teacher.base.BaseActivity
import com.lancoo.znbkxx.teacher.model.data.*
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.viewmodel.UserInfoViewModel
import com.lancoo.znbkxx.teacher.widget.DialogDiagnosisHint
import com.lancoo.znbkxx.teacher.widget.SwitchStudentWindow
import com.lancoo.znbkxx.teacher.widget.ZsdAreaPopupWindow
import kotlinx.android.synthetic.main.activity_studignosis.*
import kotlinx.android.synthetic.main.view_switch_student.view.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.*
import java.util.concurrent.TimeoutException

/**
 * @author : Admin
 * @date   : 2020/11/20
 * @desc   :
 */
class StuDiagnosisActivity : BaseActivity(), View.OnClickListener, ZsdAreaAdapter.OnSelectListener {
    private lateinit var dialog: DialogDiagnosisHint
    private lateinit var zsdArea: String
    private val number by lazy { intent.getStringExtra("number") }
    private val moveTo by lazy { intent.getIntExtra("moveTo", -1) }
    private var stuID = ""
    private var waveHelper: WaveHelper? = null
    private lateinit var timeList: ArrayList<Time>
    private var totalScore: Float = 0f
    private lateinit var viewModel: PaperViewModel
    private var position = 0
    private val validStuList = mutableListOf<ValidStu>()
    private lateinit var stuPopupWindow: SwitchStudentWindow
    private val zsdAreaList = mutableListOf<ZsdArea>()
    private val zsdWindow by lazy {
        ZsdAreaPopupWindow(zsdAreaList, this, this).apply {
            setOnDismissListener {
                val lp = window.attributes
                lp.alpha = 1.0f
                window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                window.attributes = lp
            }
        }
    }

    override fun setLayout(): Int {
        return R.layout.activity_studignosis
    }

    override fun isNeedToolBar(): Boolean {
        return false
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        zsdArea = intent.getStringExtra("zsdarea")
        viewModel = ViewModelProvider(this).get(PaperViewModel::class.java)
        lifecycle.addObserver(viewModel)
        tv_title.typeface = Typeface.createFromAsset(assets, "fonts/cool_black.TTF")
        tv_empty_total.typeface = Typeface.createFromAsset(assets, "fonts/happy.ttf")
        tv_plates.text = "${Ext.TESTNAME}认知指数"
        textView35.text = "${Ext.TESTNAME}预估成绩"
        iv_back.setOnClickListener(this)
        tv_stuname.setOnClickListener(this)
        btn_predict_change.setOnClickListener(this)
        iv_hint_words.setOnClickListener(this)
        iv_hint_grammar.setOnClickListener(this)
        iv_hint_score.setOnClickListener(this)
        iv_hint_plate.setOnClickListener(this)
        iv_hint_language.setOnClickListener(this)
        iv_hint_trait.setOnClickListener(this)
        iv_hint_study_trait.setOnClickListener(this)
        initTvHint(number)
        getStuInfoByClass()
    }

    private fun initFragment() {
        supportFragmentManager.commit {
            replace(R.id.fcv_plates, PlatesFragment().apply {
                arguments = bundleOf(Pair("zsdarea", zsdArea))
            })
            replace(R.id.fcv_words, WordsCognitionFragment().apply {
                arguments = bundleOf(Pair("zsdarea", zsdArea))
            })
            replace(R.id.fcv_grammar, GrammarCognitionFragment().apply {
                arguments = bundleOf(Pair("zsdarea", zsdArea))
            })
            replace(R.id.fcv_language, LanguageCognitionFragment())
            replace(R.id.fcv_trait, ExerciseTraitFragment())
            replace(R.id.fcv_study_trait, StudyTraitFragment())
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initAnalysis(info: TrailInfo) {
        tv_predict.text = BigDecimal(info.PersonalScore).stripTrailingZeros().toPlainString()
        tv_totalscore.text = HtmlUtils.setText(getString(R.string.total_score,
                BigDecimal(info.TotalScore).stripTrailingZeros().toPlainString()))
        val weekUp = BigDecimal(info.RiseScore).stripTrailingZeros().toPlainString()
        val drawableUp = ContextCompat.getDrawable(this, R.mipmap.aibk_icon_up)
        val drawableDown = ContextCompat.getDrawable(this, R.mipmap.aibk_icon_down)
        val drawableMid = ContextCompat.getDrawable(this, R.mipmap.aibk_icon_mid)
        when {
            info.RiseScore < 0 -> {
                tv_lastweek_up.apply {
                    text = HtmlUtils.setText("较上周：<font color='#ff9900'>降低${weekUp}</font>分")
                    setCompoundDrawablesWithIntrinsicBounds(drawableDown, null, null, null)
                }
            }
            info.RiseScore > 0 -> {
                tv_lastweek_up.apply {
                    text = HtmlUtils.setText("较上周：<font color='#22d7bb'>提升${weekUp}</font>分")
                    setCompoundDrawablesWithIntrinsicBounds(drawableUp, null, null, null)
                }
            }
            else -> {
                tv_lastweek_up.apply {
                    text = HtmlUtils.setText("较上周：<font color='#00afff'>无变化</font>")
                    setCompoundDrawablesWithIntrinsicBounds(drawableMid, null, null, null)
                }
            }
        }
        val totalUp = BigDecimal(info.OverallScore).stripTrailingZeros().toPlainString()
        when {
            info.OverallScore < 0 -> {
                tv_total_up.apply {
                    text = HtmlUtils.setText("总体：<font color='#ff9900'>降低${totalUp}</font>分")
                    setCompoundDrawablesWithIntrinsicBounds(drawableDown, null, null, null)
                }
            }
            info.OverallScore > 0 -> {
                tv_total_up.apply {
                    text = HtmlUtils.setText("总体：<font color='#22d7bb'>提升${totalUp}</font>分")
                    setCompoundDrawablesWithIntrinsicBounds(drawableUp, null, null, null)
                }
            }
            else -> {
                tv_total_up.apply {
                    text = HtmlUtils.setText("总体：<font color='#00afff'>无变化</font>")
                    setCompoundDrawablesWithIntrinsicBounds(drawableMid, null, null, null)
                }
            }
        }
        val percent = if (info.TotalScore == 0.toDouble()) {
            0f
        } else {
            (info.PersonalScore / info.TotalScore).toFloat()
        }
        cb.setPercentData(percent * 100, "%", DecelerateInterpolator(), 0)
        waveView.apply {
            waterLevelRatio = percent
            setBorder(2, Color.parseColor("#e5f9ff"))
            setWaveColor(Color.parseColor("#00aaff"), Color.parseColor("#00b4ff"))
        }
        waveHelper = WaveHelper(waveView)
        waveHelper?.start()
    }

//    @SuppressLint("CheckResult", "SetTextI18n")
//    private fun getStuGrade() {
//        val method = BkApiMethods(this)
//        val params = BkApiMethods.Paramas()
//        params["StuID"] = stuID
//        params["StageNo"] = Ext.STAGE_NO
//        params["ZsdArea"] = zsdArea
//        method.getCognitiveGradeForCenter(Ext.RZZD_URL, params).subscribe({
//            if (it.Code == 1) {
//                bindImageFromUrl(iv_head, it.Data.PhotoPath)
//                tv_beat_num.text = "认知指数：${it.Data.CurrentIndex.toInt()}分"
//                iv_rank.setImageResource(when (it.Data.cognitiveGrade.CognitiveGradeName) {
//                    "学童", "童生" -> R.mipmap.aibk_icon_rank_star1
//                    "学民", "秀才" -> R.mipmap.aibk_icon_rank_star2
//                    "学霸", "举人" -> R.mipmap.aibk_icon_rank_star3
//                    else -> R.mipmap.aibk_icon_rank_star4
//                })
//                tv_level.text = "LV.${
//                when (it.Data.cognitiveGrade.CognitiveGradeID) {
//                    "认知I级" -> 1
//                    "认知Ⅱ级" -> 2
//                    "认知Ⅲ级" -> 3
//                    else -> 4
//                }
//                }-${it.Data.cognitiveGrade.Level}"
//            } else {
//            }
//        }, {
//            val error: String = if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
//                getString(R.string.aibk_network_timeout)
//            } else {
//                getString(R.string.aibk_server_sick)
//            }
//        })
//    }

    @SuppressLint("CheckResult")
    private fun getRzzdInfo() {
        val method = BkApiMethods(this)
        val params = BkApiMethods.Paramas()
        params["StuID"] = stuID
        method.getStuPerformTrail(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                timeList = it.Data.TimeList
                totalScore = it.Data.TotalScore.toFloat()
                if (it.Data.PersonalScore == 0.toDouble()) {
                    cb.visibility = View.GONE
                    textView12.visibility = View.GONE
                    waveView.visibility = View.GONE
                    tv_predict.visibility = View.GONE
                    textView36.visibility = View.GONE
                    tv_totalscore.visibility = View.GONE
                    tv_lastweek_up.visibility = View.GONE
                    tv_total_up.visibility = View.GONE
                    btn_predict_change.visibility = View.GONE
                    tv_empty.visibility = View.VISIBLE
                } else {
                    cb.visibility = View.VISIBLE
                    textView12.visibility = View.VISIBLE
                    waveView.visibility = View.VISIBLE
                    tv_predict.visibility = View.VISIBLE
                    textView36.visibility = View.VISIBLE
                    tv_totalscore.visibility = View.VISIBLE
                    tv_lastweek_up.visibility = View.VISIBLE
                    tv_total_up.visibility = View.VISIBLE
                    btn_predict_change.visibility = View.VISIBLE
                    tv_empty.visibility = View.GONE
                    initAnalysis(it.Data)
                }
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String =
                    if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                        getString(R.string.aibk_network_timeout)
                    } else {
                        getString(R.string.aibk_server_sick)
                    }
            MyToast.showToast(error)
        })
    }

    @SuppressLint("CheckResult", "SetTextI18n")
    fun getZsdArea() {
        val methods = BkApiMethods(this)
        val params = BkApiMethods.Paramas()
        params["Stage"] = Ext.STAGE_NO
        methods.getZsdArea(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                zsdAreaList.clear()
                zsdAreaList.addAll(it.Data)
                initTvHint(when (zsdArea) {
                    "A" -> it.Data[0].Number.toString()
                    "B" -> it.Data[1].Number.toString()
                    else -> it.Data[2].Number.toString()
                })
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String =
                    if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                        getString(R.string.aibk_network_timeout)
                    } else {
                        getString(R.string.aibk_server_sick)
                    }
            MyToast.showToast( error)
        })
    }

    @SuppressLint("CheckResult")
    private fun getStudyAdvice() {
        val method = BkApiMethods(this)
        val params = BkApiMethods.Paramas()
        params["ZsdArea"] = zsdArea
        params["StageNo"] = when (Ext.GLOBAL_GRADE) {
            "K6", "K7", "K8", "K9" -> "B"
            else -> "C"
        }
        params["ProvinceId"] = CurrentUser.ProvinceID
        params["CityId"] = CurrentUser.CityID
        params["StuID"] = stuID
        method.getStudyAdvice(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                initAdvice(it.Data)
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String =
                    if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                        getString(R.string.aibk_network_timeout)
                    } else {
                        getString(R.string.aibk_server_sick)
                    }
            MyToast.showToast(error)
        })
    }

    @SuppressLint("CheckResult", "SetTextI18n")
    private fun getStuInfoByClass() {
        val method = BkApiMethods(this)
        val params = BkApiMethods.Paramas()
        method.getStuInfoByClass(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                validStuList.clear()
                validStuList.addAll(it.Data.ClassStuInfo)
                stuID = intent.getStringExtra("stuId")!!
                it.Data.ClassStuInfo.forEachIndexed { index, validStu ->
                    if (stuID == validStu.StuID) position = index
                }
                stuID = it.Data.ClassStuInfo[position].StuID?:""
                viewModel.StuID.value = stuID
                it.Data.ClassStuInfo[position].Checked = true
                stuPopupWindow = SwitchStudentWindow(this, validStuList)
                stuPopupWindow.contentView.tv_confirm.setOnClickListener(this)
                stuPopupWindow.contentView.iv_close.setOnClickListener(this)
                stuPopupWindow.setOnDismissListener {
                    val lp = window.attributes
                    lp.alpha = 1.0f
                    window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                    window.attributes = lp
                }
                tv_stuname.text = it.Data.ClassStuInfo[position].StuName
                isOpenStuRZZD()
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String =
                    if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                        getString(R.string.aibk_network_timeout)
                    } else {
                        getString(R.string.aibk_server_sick)
                    }
            MyToast.showToast(error)
        })
    }

    @SuppressLint("CheckResult")
    fun isOpenStuRZZD() {
        val method = BkApiMethods(this)
        val params = BkApiMethods.Paramas()
        params["StuID"] = stuID
        method.isOpenStuRZZD(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                if (it.Data) {
                    nsv.visibility = View.VISIBLE
                    tv_empty_total.visibility = View.GONE
                    initFragment()
                    getRzzdInfo()
                    getStudyAdvice()
                    when (moveTo) {
                        0 -> nsv.scrollTo(0, tv_words.top)
                        1 -> nsv.scrollTo(0, tv_grammar_.top)
                    }
                } else {
                    nsv.visibility = View.GONE
                    tv_empty_total.visibility = View.VISIBLE
                }
                getZsdArea()
            } else {
                nsv.visibility = View.GONE
                tv_empty_total.visibility = View.VISIBLE
            }
        }, {
            nsv.visibility = View.GONE
            tv_empty_total.visibility = View.VISIBLE
        })
    }

    private fun initTvHint(number: String) {
        tv_klg.text = HtmlUtils.setText(
                "以下诊断报告基于${Ext.TESTNAME}教材及大纲${number}⇌个知识点及学生历次学习轨迹(查看个人试卷作答轨迹)数据分析得来")
        val strInfo = tv_klg.text
        val indexStart = strInfo.indexOf(number)
        val indexEnd = indexStart + number.length + 1
        val indexStart2 = indexStart + number.length + 14
        val indexEnd2 = indexStart + number.length + 26
        val spanStr = SpannableString(strInfo)
        spanStr.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                zsdWindow.showAtLocation(zsdWindow.contentView, Gravity.BOTTOM, 0, 0)
                val lp = window.attributes
                lp.alpha = 0.8f
                window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                window.attributes = lp
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.isUnderlineText = true
                ds.color = Color.parseColor("#fff600")
            }
        }, indexStart, indexEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        spanStr.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity(Intent(this@StuDiagnosisActivity,
                        StuStudyAnalysisActivity::class.java).apply {
                    putExtra("stuId", stuID)
                })
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = Color.parseColor("#fff600")
            }
        }, indexStart2, indexEnd2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        tv_klg.text = spanStr
        tv_klg.movementMethod = LinkMovementMethod.getInstance()
    }

    @SuppressLint("SetTextI18n")
    private fun initAdvice(data: StudyAdviceInfo) {
        val bmp = BitmapFactory.decodeResource(resources, R.mipmap.aibk_icon_star)
        val height = bmp.height
        if (data.Vocabulary.Conclusion in 1..3) {
            cl_vocabulary.visibility = View.VISIBLE
            cl_vocabulary.setOnClickListener(this)
            tv_advice_words.text = "您当前常考词汇掌握率${
            when (data.Vocabulary.Conclusion) {
                1 -> "较低"
                2 -> "一般"
                else -> "较好"
            }
            }（${
            when (data.Vocabulary.Conclusion) {
                1, 2 -> "仅"
                else -> "有"
            }
            }<font color='#00afff'>${
            BigDecimal(data.Vocabulary.MasteryRate.toString()).multiply(BigDecimal(100))
                    .setScale(1, RoundingMode.HALF_UP)
                    .stripTrailingZeros().toPlainString()
            }%</font>），${
            when (data.Vocabulary.Conclusion) {
                1 -> "建议优先学习常考生词，共"
                2 -> "建议适当拓展学习部分超纲词汇，共"
                else -> "建议拓展学习全部超纲词汇，共"
            }
            }<font color='#00afff'>${data.Vocabulary.WordStudy}</font>个。".let {
                HtmlUtils.setText(it)
            }
            rb_vocabulary.apply {
                layoutParams.height = height
                layoutParams.width = ConstraintLayout.LayoutParams.WRAP_CONTENT
                rb_vocabulary.layoutParams = layoutParams
                rb_vocabulary.rating = data.Vocabulary.Star.toFloat()
            }
        } else {
            cl_vocabulary.visibility = View.GONE
        }
        if (data.Grammar.Conclusion == 1) {
            cl_grammar.visibility = View.VISIBLE
            cl_grammar.setOnClickListener(this)
            tv_grammar.text = "您当前<b>${
            if (data.Grammar.WeakGrammarList.size < 2) data.Grammar.WeakGrammarList[0] else data.Grammar.WeakGrammarList[0] + "、" + data.Grammar.WeakGrammarList[1]
            }</b>等<font color=\"#9B52F0\">${
            data.Grammar.WeakGrammarNumber
            }</font>个句法/语法专题较薄弱，建议加强句法/语法专题的学习。".let {
                HtmlUtils.setText(it)
            }
            rb_grammar.apply {
                layoutParams.height = height
                layoutParams.width = ConstraintLayout.LayoutParams.WRAP_CONTENT
                rb_grammar.layoutParams = layoutParams
                rb_grammar.rating = data.Grammar.Star.toFloat()
            }
        } else {
            cl_grammar.visibility = View.GONE
        }
        if (data.QType.Conclusion == 1) {
            cl_type.visibility = View.VISIBLE
            cl_type.setOnClickListener(this)
            val strList = data.QType.WeakTypeList.split("、")
            tv_type.text = "您当前<b>${
            if (strList.size < 2) strList[0] else strList[0] + "、" + strList[1]
            }</b>等<font color=\"#31C8D4\">${
            data.QType.WeakTypeNumber
            }</font>个题型掌握较差，建议加强训练。".let {
                HtmlUtils.setText(it)
            }
            rb_type.apply {
                layoutParams.height = height
                layoutParams.width = ConstraintLayout.LayoutParams.WRAP_CONTENT
                rb_type.layoutParams = layoutParams
                rb_type.rating = data.QType.Star.toFloat()
            }
        } else {
            cl_type.visibility = View.GONE
        }
        if (data.WrongQues.Conclusion == 1) {
            cl_wrong.visibility = View.VISIBLE
            cl_wrong.setOnClickListener(this)
            tv_wrong.text = "您当前错题共<font color='#ED4B4B'>${
            data.WrongQues.WrongNumber
            }</font>道，建议您尽早巩固。".let {
                HtmlUtils.setText(it)
            }
            rb_wrong.apply {
                layoutParams.height = height
                layoutParams.width = ConstraintLayout.LayoutParams.WRAP_CONTENT
                rb_wrong.layoutParams = layoutParams
                rb_wrong.rating = data.WrongQues.Star.toFloat()
            }
        } else {
            cl_wrong.visibility = View.GONE
        }
        val sbSkill = StringBuffer()
        if (data.WeakSkill.TL == 2) sbSkill.append("听力、")
        if (data.WeakSkill.KY == 2) sbSkill.append("口语、")
        if (data.WeakSkill.YD == 2) sbSkill.append("阅读、")
        if (data.WeakSkill.XZ == 2) sbSkill.append("写作、")
        if (sbSkill.isEmpty()) {
            cl_skill.visibility = View.GONE
        } else {
            cl_skill.visibility = View.VISIBLE
            cl_skill.setOnClickListener(this)
            tv_skill.text = HtmlUtils.setText("建议您提高<font color='#1CBF3B'>${
            sbSkill.substring(0, sbSkill.length - 1)
            }能力</font>，增加${sbSkill.substring(0, sbSkill.length - 1)}训练量噢~")
            rb_skill.apply {
                layoutParams.height = height
                layoutParams.width = ConstraintLayout.LayoutParams.WRAP_CONTENT
                rb_skill.layoutParams = layoutParams
                rb_skill.rating = data.WeakSkill.Star.toFloat()
            }
        }
        if (!data.MethodOfStudy.StudyTime.IsCons && !data.MethodOfStudy.StudyEfficiency.IsCons && !data.MethodOfStudy.WrongRate.IsCons) {
            cl_advice.visibility = View.GONE
        } else {
            val hintList = mutableListOf<String>()
            if (data.MethodOfStudy.StudyTime.IsCons) {
                hintList.add("您的学习时长较短（仅<font color='#FF9900'>${
                data.MethodOfStudy.StudyTime.Time
                }</font>小时），建议增加学习投入。")
            }
            if (data.MethodOfStudy.StudyEfficiency.IsCons) {
                hintList.add("您的学习效率较低，建议提高<font color='#FF9900'>学习专注度</font>，并注意掌握一些高效的学习方法。")
            }
            if (data.MethodOfStudy.WrongRate.IsCons) {
                hintList.add("您做题较马虎，建议做题时<font color='#FF9900'>认真审题、仔细答题。</font>)")
            }
            tv_hint_a.text = ""
            tv_hint_b.text = ""
            tv_hint_c.text = ""
            hintList.forEachIndexed { index, str ->
                when (index) {
                    0 -> tv_hint_a.text = HtmlUtils.setText("${
                    if (hintList.size > 1) "${index + 1}." else ""
                    }${str}")
                    1 -> tv_hint_b.text = HtmlUtils.setText("${index + 1}.${str}")
                    else -> tv_hint_c.text = HtmlUtils.setText("${index + 1}.${str}")
                }
            }
            tv_hint_a.visibility = if (tv_hint_a.text.isEmpty()) View.GONE else View.VISIBLE
            tv_hint_b.visibility = if (tv_hint_b.text.isEmpty()) View.GONE else View.VISIBLE
            tv_hint_c.visibility = if (tv_hint_c.text.isEmpty()) View.GONE else View.VISIBLE
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> finish()
            R.id.tv_stuname -> {
                stuPopupWindow.showAtLocation(tv_stuname, Gravity.BOTTOM, 0, 0)
                val lp = window.attributes
                lp.alpha = 0.8f
                window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                window.attributes = lp
            }
            R.id.iv_close -> stuPopupWindow.dismiss()
            R.id.tv_confirm -> {
                stuPopupWindow.dismiss()
                stuID = stuPopupWindow.data.find { it.Checked }!!.StuID?:""
                viewModel.StuID.value = stuID
                tv_stuname.text = stuPopupWindow.data.find { it.Checked }!!.StuName
                isOpenStuRZZD()
            }
            R.id.btn_predict_change -> {
                val intent = Intent(this, AchievementActivity::class.java)
                intent.putExtra("timeList", timeList)
                intent.putExtra("totalScore", totalScore)
                startActivity(intent)
            }
            R.id.iv_hint_words -> {
                dialog = DialogDiagnosisHint(5)
                dialog.show(supportFragmentManager, "")
            }
            R.id.iv_hint_grammar -> {
                dialog = DialogDiagnosisHint(6)
                dialog.show(supportFragmentManager, "")
            }
            R.id.iv_hint_score -> {
                dialog = DialogDiagnosisHint(0)
                dialog.show(supportFragmentManager, "")
            }
            R.id.iv_hint_plate -> {
                dialog = DialogDiagnosisHint(1)
                dialog.show(supportFragmentManager, "")
            }
            R.id.iv_hint_language -> {
                dialog = DialogDiagnosisHint(2)
                dialog.show(supportFragmentManager, "")
            }
            R.id.iv_hint_trait -> {
                dialog = DialogDiagnosisHint(3)
                dialog.show(supportFragmentManager, "")
            }
            R.id.iv_hint_study_trait -> {
                dialog = DialogDiagnosisHint(4)
                dialog.show(supportFragmentManager, "")
            }
        }
    }

    override fun onSelect(layoutPosition: Int) {
        zsdArea = when (layoutPosition) {
            0 -> "A"
            1 -> "B"
            else -> "C"
        }
        initTvHint(zsdAreaList[layoutPosition].Number.toString())
        initFragment()
        getStudyAdvice()
    }

    override fun onDestroy() {
        super.onDestroy()
        waveHelper?.cancel()
    }
}